import os
import win32con
import pywintypes
import win32file

LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
LOCK_SH = 0  # The default value
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
__overlapped = pywintypes.OVERLAPPED()


class flock(object):

    def __init__(self, name):
        self.file = open(name, 'w')

    def lock(self):
        try:
            hfile = win32file._get_osfhandle(self.file.fileno())
            win32file.LockFileEx(hfile, LOCK_EX, 0, 0xffff0000, __overlapped)
            return True
        except:
            print ('flock failed')
            return False

    def unlock(self):
        hfile = win32file._get_osfhandle(self.file.fileno())
        win32file.UnlockFileEx(hfile, 0, 0xffff0000, __overlapped)
        return True
